<?

/*
  Plugin Name: [RDNS]Filters
  Plugin URI: http://ricardolanes.com.br
  Description: Metabox Filters
  Version: 1.5
  Author: Ricardo Lanes
  Author URI: http://ricardolanes.com.br
 */

//ADICIONANDO O META BOX
add_action('add_meta_boxes', 'rdns_meta_box_filters');
add_action('save_post', 'rdns_meta_box_filter_save');

function rdns_meta_box_filters() {
	add_meta_box('rdns-meta-box-filters', 'Filtros dos produtos', 'rdns_meta_box_filters_start', 'produto', 'side', 'high');
}

//FORMULARIO PARA SALVAS OS DADOS
function rdns_meta_box_filters_start() {
	global $wpdb, $post;
	$post_id = $post->ID;
	wp_nonce_field('my_meta_box_nonce', 'meta_box_nonce');

	echo "<table width='100%'>";
	echo "<tr style='background-color:#CCC'>";
	echo "<td width='190'>";
	echo 'Atributo';
	echo "</td>";
	echo "<td>";
	echo 'Qtd';
	echo "</td>";
	echo "</tr>";

	$parents = $wpdb->get_results("SELECT * FROM wp_filters where parent IS NULL ORDER BY label");
	foreach ($parents as $parent) {

		echo "<tr>";
		echo "<td colspan='2'>";
		echo '&nbsp;';
		echo "</td>";
		echo "</tr>";
		
		echo "<tr>";
		echo "<td colspan='2'>";
		echo '<b>'.$parent->label.'</b>';
		echo "</td>";
		echo "</tr>";
		$filtros = $wpdb->get_results("SELECT * FROM wp_filters where parent = '$parent->id_filter' ORDER BY label");
		foreach ($filtros as $filtro) {

			$exists = $wpdb->get_results("SELECT * FROM wp_post_filter where post_id = '$post_id'");
			$checked = '';
			$qtd = '';
			foreach ($exists as $exist) {
				if ($exist->filter_id == $filtro->id_filter) {
					$qtd = $exist->qtd;
					$checked = 'checked';
					break;
				}
			}

			echo "<tr>";
			echo "<td>";
			echo '<input type="checkbox" name="meta_box_filtro[]" id="meta_box_filtro" value="' . $filtro->id_filter . '" ' . $checked . ' /> ' . $filtro->label;
			echo "</td>";
			echo "<td>";
			echo '<input type="text" name="meta_box_filter_estoque[' . $filtro->id_filter . ']" id="meta_box_filter_estoque" value="' . $qtd . '" size="5" />';
			echo "</td>";
			echo "</tr>";
		}
	}

	echo "</table>";
}

function rdns_meta_box_filter_save($post_id) {
	global $wpdb;
	if (!current_user_can('edit_post') || !isset($_POST['meta_box_nonce']) || !wp_verify_nonce($_POST['meta_box_nonce'], 'my_meta_box_nonce')) {
		return;
	}


	update_post_meta($post_id, 'meta_box_filter_estoque', $_POST['meta_box_filtro']);
	

	$wpdb->query("DELETE FROM wp_post_filter where post_id = '$post_id'");
	foreach ($_POST['meta_box_filtro'] as $id_filter) {
		$qtd = $_POST['meta_box_filter_estoque'][$id_filter] ? $_POST['meta_box_filter_estoque'][$id_filter] : 0;
		$wpdb->query("INSERT INTO wp_post_filter (post_id, filter_id, qtd) VALUES('$post_id', '$id_filter', '$qtd')");
	}
}

?>